﻿using System.Windows;
using System.Windows.Controls;

namespace FanaticRock.Theme.Helpers
{
    public class GridHelper
    {

        #region colunm defines

        public static string GetColumnDefines(DependencyObject obj)
        {
            return (string)obj.GetValue(ColumnDefinesProperty);
        }

        public static void SetColumnDefines(DependencyObject obj, string value)
        {
            obj.SetValue(ColumnDefinesProperty, value);
        }

        // Using a DependencyProperty as the backing store for ColumnDefines.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ColumnDefinesProperty =
            DependencyProperty.RegisterAttached("ColumnDefines", typeof(string), typeof(GridHelper), new PropertyMetadata(null) { PropertyChangedCallback = OnColumnDefinesChanged });

        private static void OnColumnDefinesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Grid == false) return;
            var grid = d as Grid;
            grid.ColumnDefinitions.Clear();

            var rawText = e.NewValue as string;
            var rawParts = rawText.Split(',');
            var converter = new GridLengthConverter();
            foreach (var part in rawParts)
            {
                var gridLength = (GridLength)converter.ConvertFrom(part);
                grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = gridLength });
            }
        }



        #endregion

        #region row defines

        public static string GetRowDefines(DependencyObject obj)
        {
            return (string)obj.GetValue(RowDefinesProperty);
        }

        public static void SetRowDefines(DependencyObject obj, string value)
        {
            obj.SetValue(RowDefinesProperty, value);
        }

        // Using a DependencyProperty as the backing store for RowDefines.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty RowDefinesProperty =
            DependencyProperty.RegisterAttached("RowDefines", typeof(string), typeof(GridHelper), new PropertyMetadata(null) { PropertyChangedCallback = OnRowDefinesChanged });

        private static void OnRowDefinesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is Grid == false) return;
            var grid = d as Grid;
            grid.RowDefinitions.Clear();

            var rawText = e.NewValue as string;
            var rawParts = rawText.Split(',');
            var converter = new GridLengthConverter();
            foreach (var part in rawParts)
            {
                var gridLength = (GridLength)converter.ConvertFrom(part);
                grid.RowDefinitions.Add(new RowDefinition() { Height = gridLength });
            }
        }



        #endregion



    }
}
